package org.example.project.service.impl;

import org.example.project.service.UrlTitleService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * @author weibin
 * @since 2025/10/13 19:46
 */
@Service
public class UrlTitleServiceImpl implements UrlTitleService {

    @Override
    public String getUrlTitle(String url) {
        try {
            // 参数会进行 url 编码，所以这里解码一下
            String decodeUrl = URLDecoder.decode(url, StandardCharsets.UTF_8);
            Document doc = Jsoup.connect(decodeUrl)
                    // 模拟浏览器访问
                    .userAgent("Mozilla/5.0")
                    // 10秒超时
                    .timeout(10000)
                    .get();
            return doc.title();
        } catch (Exception e) {
            return "无法获取标题: " + e.getMessage();
        }
    }
}
